import { PluginOption, defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';//为打包后的文件提供传统浏览器兼容性支持
import legacy from '@vitejs/plugin-legacy';
import { resolve } from 'path';
import viteCompression from 'vite-plugin-compression';//压缩文件
import {visualizer} from "rollup-plugin-visualizer";//性能分析可视化
// import commonjsExternals from 'vite-plsugin-commonjs-externals';
// https://vitejs.dev/config/
function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir);
}
//console.log(env);   //变量在命令行里打印出来

export default ({mode})=>{
    const env=loadEnv(mode, process.cwd());   // 获取.env文件里定义的环境变量
    return defineConfig({
    base:"",
    build:{
      brotliSize:false,
      chunkSizeWarningLimit:2000,
      rollupOptions:{
        output:{
          manualChunks(id){ // 分包
            if(id.includes('node_modules')){
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          }
        }
      }
    },
    server:{
     host:"0.0.0.0",
     port:8083,
           open: true,
      proxy: {
        // https://cn.vitejs.dev/config/#server-proxy
        '/dev-api': {
          target: 'http://vue.ruoyi.vip/prod-api',
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, '')
        }
      }
    },
    resolve: {
      alias: [
        // /@/xxxx => src/xxxx
        {
          find: /\/@\//,
          replacement: pathResolve('src') + '/',
        },
        {
          find: /\/@ts\//,
          replacement: pathResolve('src') + '/',
        },
        // /#/xxxx => types/xxxx
        {
          find: /\/#\//,
          replacement: pathResolve('types') + '/',
        },
        // ['@vue/compiler-sfc', '@vue/compiler-sfc/dist/compiler-sfc.esm-browser.js'],
      ]
    },
    plugins: [
      vue(),
      viteCompression(),
      legacy({
        targets: ['defaults', 'not IE 11']
      }),
      // commonjsExternals({
      //   externals: ['path'] //这里
      // })
      visualizer() as PluginOption
    ]
  })
}
